const tb = document.querySelector('#tb')
const form = document.querySelector('form')
const btncc = document.querySelector('#btnAcc')
// const a = document.querySelectorAll('a')
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const renderBooks = async () => {
  const fors = await axios.get('/api/getbooks')
  const { data: res } = fors
  const { data } = res
  console.log(data)
  const html = data
    .map((item) => {
      return ` <tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td> <a href="#" data-id=${item.id}>删除</a></td>
      </tr>`
    })
    .join('')
  tb.innerHTML = html
}
renderBooks()
form.addEventListener('submit', async function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  const fore = await axios.post('/api/addbook', data)
  const { data: res } = fore
  alert(res.msg)
  if (res.data !== 201) return
  form.reset()
  renderBooks()
})
tb.addEventListener('click', async function (e) {
  if ((e.target.tagName = 'A')) {
    let id = e.target.dataset.id
    const forq = await axios.get('/api/delbook?id=' + id)
    const { data: res } = forq
    renderBooks()
  }
})
btncc.addEventListener('click', async function (e) {
  e.preventDefault()
  // console.log(1)
  const data = serialize(form, { hash: true })
  const foea = await axios.get('/api/getbooks', { params: data })
  const { data: res } = foea
  console.log(res)
  const date = res.data
  const html = date
    .map((item) => {
      return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td> <a href="#" data-id=${item.id}>删除</a></td>
    </tr>`
    })
    .join('')
  tb.innerHTML = html
})
